package com.ruoyi.process.pipemaintainence2.controller;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.entity.APIResult;
import com.ruoyi.common.enums.StateEnum;
import com.ruoyi.common.utils.BeanUtils;
import com.ruoyi.common.utils.StringUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.process.leave.domain.BizLeaveVo;
import com.ruoyi.process.pipemaintainence.domain.DrainagePipeMaintainence;
import com.ruoyi.system.domain.SysUser;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.process.pipemaintainence2.domain.TDrainagePipeMaintainence;
import com.ruoyi.process.pipemaintainence2.service.ITDrainagePipeMaintainenceService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 排水管养Controller
 *
 * @author Xianlu Tech
 * @date 2019-12-05
 */
@Controller
@RequestMapping("/process/maintainence")
public class TDrainagePipeMaintainenceController extends BaseController {

    private String prefix = "process/pipeMaintainence2/maintainence";

    @Autowired
    private ITDrainagePipeMaintainenceService tDrainagePipeMaintainenceService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    //列表
    @RequiresPermissions("process:maintainence:view")
    @GetMapping()
    public String maintainence(ModelMap map) {
        map.put("currentUser", ShiroUtils.getSysUser());
        return prefix + "/maintainence";
    }

    //待办
    @RequiresPermissions("process:maintainence:todoView")
    @GetMapping("/todo")
    public String todoItem() {
        return prefix + "/todoitemMaintainence";
    }

    //已办
    @RequiresPermissions("process:maintainence:doneView")
    @GetMapping("/done")
    public String doneItem() {
        return prefix + "/doneitemMaintainence";
    }

    //我发起的
    @RequiresPermissions("process:maintainence:startbyView")
    @GetMapping("/startby")
    public String startByOwnItem() {
        return prefix + "/startbyMaintainence";
    }


    /**
     * 查询排水管养列表（原始的接口）
     */
    @RequiresPermissions("process:maintainence:list")
    @PostMapping("/list1")
    @ResponseBody
    public TableDataInfo list(TDrainagePipeMaintainence tDrainagePipeMaintainence) {
        startPage();
        List<TDrainagePipeMaintainence> list = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceList(tDrainagePipeMaintainence);
        //也可以使用map的方式封装对象，在页面上展示出来
        //  List<Map<String, Object>> list = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceList2(tDrainagePipeMaintainence);
        return getDataTable(list);
    }

    /**
     * 查询排水管养列表 以Map的形式返回，参数以map的方式接收（改造接口：改成可以进行模糊查询）
     */
    @RequiresPermissions("process:maintainence:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody String requestParam) {
        List<Map<String, Object>> list = null;
        try {
            String decode = URLDecoder.decode(requestParam, "utf-8");
            Map<String, Object> map = StringUtil.stringToMap(decode);
            //判断是否是管理员
            if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
                map.put("createBy", ShiroUtils.getUserId());
            }
            startPage();
            list = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceList3(map);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return getDataTable(list);
    }


    /**
     * 导出排水管养列表
     */
    @RequiresPermissions("process:maintainence:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TDrainagePipeMaintainence tDrainagePipeMaintainence) {
        List<TDrainagePipeMaintainence> list = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceList(tDrainagePipeMaintainence);
        ExcelUtil<TDrainagePipeMaintainence> util = new ExcelUtil<TDrainagePipeMaintainence>(TDrainagePipeMaintainence.class);
        return util.exportExcel(list, "maintainence");
    }

    /**
     * 新增排水管养
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存排水管养
     */
    @RequiresPermissions("process:maintainence:add")
    @Log(title = "排水管养", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TDrainagePipeMaintainence tDrainagePipeMaintainence) {
        return toAjax(tDrainagePipeMaintainenceService.insertTDrainagePipeMaintainence(tDrainagePipeMaintainence));
    }

    /**
     * 修改排水管养
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        TDrainagePipeMaintainence tDrainagePipeMaintainence = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceById(id);
        mmap.put("tDrainagePipeMaintainence", tDrainagePipeMaintainence);
        return prefix + "/edit";
    }

    /**
     * 修改保存排水管养
     */
    @RequiresPermissions("process:maintainence:edit")
    @Log(title = "排水管养", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TDrainagePipeMaintainence tDrainagePipeMaintainence) {
        return toAjax(tDrainagePipeMaintainenceService.updateTDrainagePipeMaintainence(tDrainagePipeMaintainence));
    }

    /**
     * 删除排水管养
     */
    @RequiresPermissions("process:maintainence:remove")
    @Log(title = "排水管养", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(tDrainagePipeMaintainenceService.deleteTDrainagePipeMaintainenceByIds(ids));
    }


    /**
     * 待办
     *
     * @param requestParam
     * @return
     */
    @RequiresPermissions("process:maintainence:todoView")
    @PostMapping("/todo")
    @ResponseBody
    public TableDataInfo todo(@RequestBody String requestParam) {
        List<Map<String, Object>> list = null;
        try {
            String decode = URLDecoder.decode(requestParam, "utf-8");
            Map<String, Object> map = StringUtil.stringToMap(decode);
            startPage();
            list = tDrainagePipeMaintainenceService.todoTaskList(map);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return getDataTable(list);
    }


    /**
     * 已办
     *
     * @return
     */
    @RequiresPermissions("process:maintainence:doneView")
    @PostMapping("/done")
    @ResponseBody
    public TableDataInfo done() {
        List<Map<String, Object>> list = tDrainagePipeMaintainenceService.doneTask();
        return getDataTable(list);
    }


    /**
     * 我发起的
     *
     * @return
     */
    @RequiresPermissions("process:maintainence:startbyView")
    @PostMapping("/startby")
    @ResponseBody
    public TableDataInfo startByOwn() {
        List<Map<String, Object>> list = tDrainagePipeMaintainenceService.startByOwn();
        return getDataTable(list);
    }


    /**
     * 启动流程
     */
    @Log(title = "管养业务", businessType = BusinessType.UPDATE)
    @PostMapping("/submitApply")
    @ResponseBody
    public AjaxResult submitApply(String id) {
        TDrainagePipeMaintainence tDrainagePipeMaintainence = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceById(id);
        String applyUserId = ShiroUtils.getUserId().toString();
        tDrainagePipeMaintainenceService.submitApply(tDrainagePipeMaintainence, applyUserId);
        return success();
    }

    /**
     * 完成任务
     */
    @Log(title = "管养业务", businessType = BusinessType.UPDATE)
    @PostMapping("/completeTask")
    @ResponseBody
    public AjaxResult completeTask(String taskId) {
        TDrainagePipeMaintainence tDrainagePipeMaintainence = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceById(taskId);
        String applyUserId = ShiroUtils.getUserId().toString();
        tDrainagePipeMaintainenceService.submitApply(tDrainagePipeMaintainence, applyUserId);
        return success();
    }


    /**
     * 加载办理弹窗
     *
     * @param taskId
     * @return
     */
    @GetMapping("/showVerifyDialog/{taskId}")
    public String showVerifyDialog(@PathVariable("taskId") String taskId, ModelMap modelMap) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        //获得任务定义的key   adjust 整改复核   confirm 审批确认
        String taskDefinitionKey = task.getTaskDefinitionKey();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        TDrainagePipeMaintainence tDrainagePipeMaintainence = tDrainagePipeMaintainenceService.selectTDrainagePipeMaintainenceById(processInstance.getBusinessKey());
        if (BeanUtils.isNotEmpty(tDrainagePipeMaintainence)) {
            modelMap.put("tDrainagePipeMaintainence", tDrainagePipeMaintainence);
        }
        modelMap.put("taskId", taskId);
        return prefix + "/" + taskDefinitionKey;
    }


    /**
     * 完成任务
     *
     * @param taskId
     * @param tDrainagePipeMaintainence
     * @param request
     * @return
     */
    @RequestMapping(value = "/complete/{taskId}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult complete(@PathVariable("taskId") String taskId,
                               TDrainagePipeMaintainence tDrainagePipeMaintainence, HttpServletRequest request) {
        String[] opinions = request.getParameterMap().get("opinion");
        Boolean opinion = Boolean.valueOf(opinions[0]);
        String[] comments = request.getParameterMap().get("comment");
        String comment = comments[0];    // 批注
        try {
            if (StringUtils.isNotEmpty(comment)) {
                identityService.setAuthenticatedUserId(ShiroUtils.getLoginName());
                taskService.addComment(taskId, tDrainagePipeMaintainence.getProcessInstanceId(), comment);
            }
            String userId = ShiroUtils.getUserId().toString();
            tDrainagePipeMaintainenceService.complete(userId, taskId, opinion, comment);
            return success("任务已完成");
        } catch (Exception e) {
            logger.error("error on complete task {}", new Object[]{taskId, e});
            return error("完成任务失败");
        }
    }


    /**
     * 选择系统用户
     */
    @GetMapping("/selectUser")
    public String selectUser() {
        return prefix + "/selectUser";
    }

}
